package com.business.systemmanage.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.business.systemmanage.common.cont.CommonCont;
import com.business.systemmanage.common.entity.exception.BusinessException;
import com.business.systemmanage.common.util.Md5;
import com.business.systemmanage.entity.UserInfo;
import com.business.systemmanage.mapper.UserInfoMapper;
import com.business.systemmanage.service.IUserInfoService;
import com.business.systemmanage.vo.UserInfoVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author sixDog
 * @since 2019-04-12
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

    @Override
    public void register(UserInfoVO userInfoVO) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        final UserInfo one = this.getOne(new QueryWrapper<UserInfo>().lambda().eq(UserInfo::getLoginName, userInfoVO.getLoginName()));
        if(one!=null) {
            throw new BusinessException("用户名已经被注册，请修改用户名");
        }
        userInfoVO.setPassword(Md5.EncoderByMd5(userInfoVO.getPassword()));
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userInfoVO, userInfo);

        userInfo.setCreateTime(LocalDateTime.now());
        userInfo.setModifyTime(LocalDateTime.now());
        userInfo.setStatus(CommonCont.YES);
        this.save(userInfo);
    }

    @Override
    public UserInfo login(String loginName, String password) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getLoginName, loginName);
        final UserInfo userInfo = this.getOne(queryWrapper);
        if (userInfo == null) {
            throw new BusinessException("用户名不存在");
        }
        if (!Md5.checkpassword(password, userInfo.getPassword())) {
            throw new BusinessException("密码不正确");
        }
        return userInfo;
    }
}
